package com.gitee.fsmxm.ocd.service;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fsmxm
 */
@Service
public class DirectoryCleanScheduler {

    private ConcurrentLinkedQueue<File> queue;
    private ScheduledThreadPoolExecutor executor;

    public DirectoryCleanScheduler() {
        queue = new ConcurrentLinkedQueue<>();
        executor = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
            private AtomicInteger ai = new AtomicInteger();

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "dcleaner-" + ai.incrementAndGet());
            }
        });
        executor.schedule(() -> {
            final File dir = queue.poll();
            if (dir != null) {
                FileUtils.deleteQuietly(dir);
                if (dir.exists()) {
                    queue.offer(dir);
                }
            }
        }, 2000, TimeUnit.MILLISECONDS);
    }

    public void offer(File file) {
        queue.offer(file);
    }

    public void close() {
        executor.shutdown();
    }
}
